package com.yu.yupicture.controller;



import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yu.yupicture.Untils.ThrowUntil;
import com.yu.yupicture.annotation.AuthCheck;
import com.yu.yupicture.api.aliyunApi.model.ImageEditResponse;
import com.yu.yupicture.api.aliyunApi.model.ImageGetResponse;
import com.yu.yupicture.api.aliyunApi.sub.aliImageEditRequestApi;
import com.yu.yupicture.common.BaseReponse;
import com.yu.yupicture.common.DeleteRequest;
import com.yu.yupicture.common.Result;
import com.yu.yupicture.constans.CacheConstans;
import com.yu.yupicture.constans.UserConstans;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import com.yu.yupicture.manger.cache.localCache;
import com.yu.yupicture.manger.cache.muchCache;
import com.yu.yupicture.model.domain.dto.picture.*;
import com.yu.yupicture.model.domain.entry.Picture;
import com.yu.yupicture.model.domain.entry.User;
import com.yu.yupicture.model.domain.vo.PictureVO;
import com.yu.yupicture.service.PictureService;
import com.yu.yupicture.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import java.util.Arrays;
import java.util.List;

@Api(tags = "图片相关接口")
@Slf4j
@RestController
@RequestMapping("/picture")
public class pictureController {

    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;

    @Resource
    private localCache localCache;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private muchCache muchCache;
    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private aliImageEditRequestApi aliImageEditRequestApi;

    @GetMapping("/tag_category")
    public BaseReponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return Result.success(pictureTagCategory);
    }


    /**
     * 上传图片（可重新上传）
     */
    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public BaseReponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        if (user == null) {
            throw new biusnessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return Result.success(pictureService.uploadPicture(user, pictureUploadRequest, multipartFile));
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @ApiOperation("通过url上传图片")
    @PostMapping("/upload/url")
    public BaseReponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(loginUser,pictureUploadRequest, fileUrl);
        return Result.success(pictureVO);
    }


    /**
     * 分页查询-管理端
     *
     * @throws IOException
     */
    @PostMapping("/list/page")
    @ApiOperation("分页查询-管理端")
    @AuthCheck(value = UserConstans.ADMIN)
    public BaseReponse<Page<Picture>> page(@RequestBody PictureQueryRequest pictureQueryRequest) throws IOException {
        ThrowUntil.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        return Result.success(pictureService.page(pictureQueryRequest));
    }

    /**
     * 分页查询-用户端
     *
     * @throws IOException
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页查询-用户端")
    public BaseReponse<Page<PictureVO>> pageVo(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) throws IOException {
        ThrowUntil.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        User user = userService.getLoginUser(request);
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR, "未登录");
        //限制爬虫
        ThrowUntil.throwIf(pictureQueryRequest.getPageSize() > 20, ErrorCode.PARAMS_ERROR, "请求参数过大");
        return Result.success(pictureService.pageVo(pictureQueryRequest, user));
    }

    @ApiOperation("根据id查询图片-管理员")
    @GetMapping("/get")
    @AuthCheck(value = UserConstans.ADMIN)
    public BaseReponse<Picture> getPictureById(@RequestParam("id") Long id) {
        return Result.success(pictureService.getPictureById(id));
    }

    @ApiOperation("根据id查询图片-用户端")
    @GetMapping("/get/vo")
    public BaseReponse<PictureVO> getPictureById(@RequestParam("id") Long id, HttpServletRequest request) {
        ThrowUntil.throwIf(userService.getLoginUser(request) == null, ErrorCode.NOT_LOGIN_ERROR);
        return Result.success(pictureService.getPictureVoById(id,userService.getLoginUser(request)));
    }

    @ApiOperation("根据id删除图片-管理员")
    @PostMapping("/delete")
    @AuthCheck(value = UserConstans.ADMIN)
    public BaseReponse<Boolean> deletePictureById(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        if (!pictureService.isAdmin(user) && !user.getId().equals(deleteRequest.getId())) {
            throw new biusnessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        return Result.success(pictureService.deleteById(deleteRequest.getId()));
    }
    @PostMapping("/edit")
    @ApiOperation("更新图片-用户端")
    public BaseReponse<Boolean> UserupdatePicture(@RequestBody PictureEditRequest pictureEditRequest,HttpServletRequest  request){
        User user = userService.getLoginUser(request);
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        return Result.success(pictureService.UserupdatePcture(pictureEditRequest,user));
    }

    @AuthCheck(value = UserConstans.ADMIN)
    @PostMapping("/update")
    @ApiOperation("更新图片-管理端")
    public BaseReponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,HttpServletRequest request){
        User user = userService.getLoginUser(request);
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        return Result.success(pictureService.updatePicture(pictureUpdateRequest, user));
    }

    @AuthCheck(value = UserConstans.ADMIN)
    @PostMapping("/review")
    @ApiOperation("审核图片-管理端")
    public BaseReponse<Boolean> reviewPicture(@RequestBody PictureReviewRequest pictureReviewRequest,HttpServletRequest request){
        User user = userService.getLoginUser(request);
        return Result.success(pictureService.reviewPicture(pictureReviewRequest,user));
    }

    @ApiOperation("批量上传图片")
    @PostMapping("/upload/batch")
    @AuthCheck(value = UserConstans.ADMIN)
    public BaseReponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUntil.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return Result.success(uploadCount);
    }


    /**
     * 分页查询-用户端
     *
     * @throws IOException
     */
    @PostMapping("/list/page/vo/cache")
    @ApiOperation("分页查询-用户端")
    public BaseReponse<Page<PictureVO>> pageVoAndCache2(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) throws IOException {
        ThrowUntil.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        User user = userService.getLoginUser(request);
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR, "未登录");
        //限制爬虫
        ThrowUntil.throwIf(pictureQueryRequest.getPageSize() > 20, ErrorCode.PARAMS_ERROR, "请求参数过大");

        //多级缓存
        String keyCondition = DigestUtils.md5DigestAsHex(JSONUtil.toJsonStr(pictureQueryRequest).getBytes());
        String localKey=CacheConstans.LOCAL_CACHE_PREFIX+keyCondition;
        String redisKey=CacheConstans.PAGE_PIC__PRV+keyCondition;
        Page<PictureVO> page =
                muchCache.
                        cache2(localKey, redisKey,
                                new TypeReference<Page<PictureVO>>() {},
                                pictureQueryRequest,
                                k -> pictureService.pageVo(pictureQueryRequest, user));
        return Result.success(page);
    }


    /**
     * 以图搜图功能
     *
     * @param searchPictureByColorRequest
     * @param request
     * @return
     */

    @ApiOperation("以图搜图功能")
    @PostMapping("/search/color")
    public BaseReponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUntil.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getLoginUser(request);
        return Result.success(pictureService.searchPictureVoByImage(searchPictureByColorRequest.getSpaceId(), searchPictureByColorRequest.getPicColor(), user));
    }

    /**
     * 批处理操作
     */

    @PostMapping("/edit/batch")
    public BaseReponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUntil.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.batchEdit(pictureEditByBatchRequest, loginUser);
        return Result.success(true);
    }

    /**
     * ai扩图
     */
    @ApiOperation("ai扩图")
    @PostMapping("/out_painting/create_task")
    public BaseReponse<String> aiExpand(@RequestBody CreatePictureOutPaintingTaskRequest aiExpandRequest, HttpServletRequest request) {
        ThrowUntil.throwIf(aiExpandRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        ThrowUntil.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ImageEditResponse imageEditResponse = pictureService.aiExpand(aiExpandRequest);
            return Result.success(imageEditResponse.getOutput().getTaskId());
    }

    @ApiOperation("获取ai扩图结果")
    @GetMapping("/out_painting/get_task")
    public BaseReponse<ImageGetResponse> getAiExpandResult(@RequestParam("taskId") String taskId) {
        ImageGetResponse imageGetResponse = aliImageEditRequestApi.getResult(taskId);
        return Result.success(imageGetResponse);
    }


}
